<?php

namespace App\Http\Controllers\Answer;

use App\Helpers\Tools;
use App\Models\ChallengeLevel;
use App\Models\ChallengeRecord;
use App\Models\Member;
use App\Http\Controllers\Controller;
use App\Models\Record;
use App\Models\Title;
use App\Services\WeChatProgramService;

class AnswerController extends Controller
{
    // 微信授权
    public function weChatUser()
    {
        $code = request('code');

        // 获取微信信息
        $weChatProgramService = new WeChatProgramService();
        $info = $weChatProgramService->login($code);

        return Tools::setData($info);
    }

        // 获取用户信息
    public function memberInfo()
    {
        $openid = request('openid');
        $nickname = request('nickname');
        $avatarUrl = request('avatarUrl');

        $memberInfo = Member::Openid($openid)->first();

        if (!$memberInfo) {
            $data['openid'] = $openid;
            $data['nickname'] = $nickname; //
            $data['avatar_url'] = $avatarUrl; //
            $data['created_at'] = date('Y-m-d H:i:s');
            $data['updated_at'] = date('Y-m-d H:i:s');

            $member = new Member();
            $id = $member->insertGetId($data);

            $memberInfo = $data;
            $memberInfo['id'] = $id;
        } else {
            $memberInfo = $memberInfo->toArray();
        }

        $this->sign($memberInfo['id']);

        return Tools::setData($memberInfo);
    }

    // 获取用户关卡资料
    public function challengeLevel()
    {
        $memberId = request('memberId');

        $challengeLevel = ChallengeLevel::Member($memberId)->first();

        $arr = [];
        if ($challengeLevel) {
            $arr[1] = [
                'name' => '初级挑战',
                'level' => $challengeLevel['challenge1']
            ];
            $arr[2] = [
                'name' => '中级挑战',
                'level' => $challengeLevel['challenge2']
            ];
            $arr[3] = [
                'name' => '高级挑战',
                'level' => $challengeLevel['challenge3']
            ];
            $arr[4] = [
                'name' => '巅峰关卡',
                'level' => $challengeLevel['challenge4']
            ];
            $arr[5] = [
                'name' => '终级关卡',
                'level' => $challengeLevel['challenge5']
            ];
        }

        return Tools::setData($arr);
    }

    // 闯关答题记录
    public function challengeRecord()
    {
        $memberId = request('memberId');
        $challengeLevel = request('challengeLevel');
        $count = request('count');
        $timer = request('timer');

        $challengeRecord = new ChallengeRecord();
        $challengeRecord->member_id = $memberId;
        $challengeRecord->challenge_level = $challengeLevel;
        $challengeRecord->count = $count;
        $challengeRecord->timer = $timer;

        $res = $challengeRecord->save();

        $this->updateChallengeLevel($memberId, $challengeLevel, $count);

        // 修改通关状态
        $this->make($memberId, $challengeLevel);

        if ($res) {
            return Tools::success('添加成功');
        }

        return Tools::error('添加失败');
    }

    // 修改关卡级别
    public function updateChallengeLevel($memberId, $challengeLevel, $count)
    {
        if ($count <= 4) {
            $level = 1;
        } else if ($count <= 9) {
            $level = 2;
        } else if ($count <= 10) {
            $level = 3;
        }

        $memberChallengeLevel = ChallengeLevel::Member($memberId)->first();

        switch ($challengeLevel) {
            case 1:
                if ($level > $memberChallengeLevel->challenge1) {
                    $memberChallengeLevel->challenge1 = $level;
                }
                break;
            case 2:
                if ($level > $memberChallengeLevel->challenge2) {
                    $memberChallengeLevel->challenge2 = $level;
                }
                break;
            case 3:
                if ($level > $memberChallengeLevel->challenge3) {
                    $memberChallengeLevel->challenge3 = $level;
                }
                break;
            case 4:
                if ($level > $memberChallengeLevel->challenge4) {
                    $memberChallengeLevel->challenge4 = $level;
                }
                break;
            case 5:
                if ($level > $memberChallengeLevel->challenge5) {
                    $memberChallengeLevel->challenge5 = $level;
                }
                break;
            default:
        }

        $memberChallengeLevel->save();
    }

    // 发起挑战
    public function pkSponsor()
    {
        $data = request()->all(['memberId', 'count', 'timer']);

        $record = new Record();

        $arr['challenge_member_id'] = $data['memberId'];
        $arr['challenge_count'] = $data['count'];
        $arr['challenge_timer'] = $data['timer'];
        $arr['created_at'] = date('Y-m-d H:i:s');
        $arr['updated_at'] = date('Y-m-d H:i:s');

        $id = $record->insertGetId($arr);

        $this->addChallengeCount($data['memberId']);

        if ($id) {
            return Tools::setData([
                'record_id' => $id
            ]);
        }

        return Tools::error('添加失败');
    }

    // 获取挑战信息
    public function pkRecordInfo()
    {
        $recordId = request('recordId');

        $recordInfo = Record::with('challengeMember')->find($recordId);

        return Tools::setData($recordInfo);
    }

    // 应战
    public function pkAccept()
    {
        $data = request()->all(['recordId', 'memberId', 'count', 'timer']);
        $victoryMemberId = 0;
        $defeatedMemberId = 0;

        $record = Record::find($data['recordId']);

        // 获取获胜者信息
        if ($record->challenge_count == $data['count']) {
            if ($record->challenge_timer < $data['timer']) {
                $victoryMemberId = $record->challenge_member_id;
                $defeatedMemberId = $data['memberId'];
            } else {
                $victoryMemberId = $data['memberId'];
                $defeatedMemberId = $record->challenge_member_id;
            }
        } else {
            if ($record->challenge_count > $data['count']) {
                $victoryMemberId = $record->challenge_member_id;
                $defeatedMemberId = $data['memberId'];
            } else {
                $victoryMemberId = $data['memberId'];
                $defeatedMemberId = $record->challenge_member_id;
            }
        }

        $record->accept_member_id = $data['memberId'];
        $record->victory_member_id = $victoryMemberId;
        $record->defeated_member_id = $defeatedMemberId;
        $record->accept_count = $data['count'];
        $record->accept_timer = $data['timer'];

        $res = $record->save();

        $this->addVictoryCount($victoryMemberId);

        if ($res) {
            return Tools::success('应战记录成功');
        }

        return Tools::error('应战记录失败');
    }

    // 排行榜
    public function seniority()
    {

    }

    // 排行榜
    public function title()
    {
        $memberId = request('memberId');

        $title = Title::Member($memberId)->first();

        return Tools::setData($title);
    }

    // 挑战记录
    public function pkRecord()
    {
        $memberId = request('memberId');
        $records = Record::MemberRecord($memberId)->get();

        $arr = [];
        foreach ($records as $key => $val) {
            if ($val->victory_member_id == $memberId) {
                $member = Member::find($val->defeated_member_id);
                $nickname = $member->nickname;

                $arr[] = "我在好友挑战赛中战胜了$nickname";
            } else {
                $member = Member::find($val->victory_member_id);
                $nickname = $member->nickname;

                $arr[] = "我在好友挑战赛中被{$nickname}击败";
            }
        }

        if ($arr) {
            return Tools::setData($arr);
        }

        $arr[] = '暂无挑战记录';
        return Tools::setData($arr);
    }

    // 每次获取用户信息时，都签到一次
    protected function sign($memberId)
    {
        $title = Title::Member($memberId)->first();
        $title->sign = $title->sign + 1;
        $title->save();
    }

    // 如果闯关的级别比之前的高，那么添加闯关的关数
    protected function make($memberId, $challengeLevel)
    {
        $title = Title::Member($memberId)->first();

        if ($challengeLevel > $title->make) {
            $title->make = $challengeLevel;
            $title->save();
        }
    }

    // 发起挑战次数添加
    protected function addChallengeCount($memberId)
    {
        $title = Title::Member($memberId)->first();
        $title->challenge = $title->challenge + 1;
        $title->save();
    }

    // 获胜次数添加
    protected function addVictoryCount($memberId)
    {
        $title = Title::Member($memberId)->first();
        $title->victory = $title->victory + 1;
        $title->save();
    }

}
